package com.zqq.webcloud;

import android.net.Uri;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 简单的网络请求
 *
 * @author zqq on 2018/9/5
 */
public class HttpRequest {

    public static final String UTF_8 = "UTF-8";
    private static String cookie = null;


    /**
     * GET请求
     */
    public static String httpGet(String actionUrl, Map<String, String> params) {
        try {
            StringBuffer urlbuff = new StringBuffer(actionUrl);
            if (params != null && params.size() > 0) {
                if (actionUrl.indexOf("?") >= 0) {
                    urlbuff.append("&");
                } else {
                    urlbuff.append("?");
                }
                for (String key : params.keySet()) {
                    urlbuff.append(key).append("=")
                            .append(URLEncoder.encode(params.get(key), UTF_8))
                            .append("&");
                }
                urlbuff.deleteCharAt(urlbuff.length() - 1);
                Log.e("---Tag-request-GET--", urlbuff.toString());
            }
            URL url = new URL(urlbuff.toString());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);// 允许输入
            conn.setDoOutput(false);// 允许输出
            conn.setUseCaches(false);// 不使用Cache
            conn.setRequestMethod("GET");

            //以下是添加请求头
            conn.setRequestProperty("Charset", UTF_8);
            conn.setRequestProperty("X-LC-Id","LiGEddCUfS94R9VBfpww9mWO-gzGzoHsz");
            conn.setRequestProperty("X-LC-Key","1YVHJJqtSrU50RGK7fH7MT87");
            conn.setRequestProperty("Content-Type","application/json");
            conn.setReadTimeout(5000);// 连接上了读取超时的时间
            conn.setConnectTimeout(5000);// 设置连接超时时间5s

            if (cookie != null) {
                conn.setRequestProperty("Cookie",cookie);
            }
            int cah = conn.getResponseCode();
            if (cah != 200) {
//                throw new RuntimeException("请求URL失败");
                Log.e("---Tag--", Integer.toString(cah));
            }
            if (conn.getHeaderField("Set-Cookie") != null) {
                cookie = conn.getHeaderField("Set-Cookie");
            }
            Log.e("--Tag--", "------------------cookie:" + cookie);
            Map<String, List<String>> keys = conn.getHeaderFields();
            for (String key : keys.keySet()) {
                List<String> list = keys.get(key);
                for (String value : list) {
                    Log.e("--Tag--", "header: key:" + key + "  values:" + value);
                }
            }
            InputStream is = conn.getInputStream();
            int ch;
            StringBuilder b = new StringBuilder();//不安全但速度快
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            is.close();
            conn.disconnect();
            return b.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * POST请求
     */
    public static String httpPost(String actionUrl, Map<String, String> params) {
        try {
            URL url = new URL(actionUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //因为这个是post请求,设立需要设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置以POST方式
            conn.setRequestMethod("POST");
            // Post 请求不能使用缓存
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
            // 要注意的是connection.getOutputStream会隐含的进行connect。

            if (cookie != null) {
                conn.setRequestProperty("Cookie", cookie);
            }
            conn.connect();
            //DataOutputStream流
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            //要上传的参数
            StringBuffer content = new StringBuffer();
            for (String key : params.keySet()) {
                //String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
                content.append(key).append("=").append(params.get(key)).append("&");
            }
            //将要上传的内容写入流中
            out.writeBytes(content.toString());
            //刷新、关闭
            out.flush();
            out.close();

            int statusCode = conn.getResponseCode();
            Log.e("", "---------------statusCode:" + statusCode);
            if (statusCode != 200) {
                throw new RuntimeException("server error");
            }
            if (conn.getHeaderField("Set-Cookie") != null) {
                cookie = conn.getHeaderField("Set-Cookie");
            }
            //获取数据
            InputStream is = conn.getInputStream();
            int ch;
            StringBuilder b = new StringBuilder();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            conn.disconnect();
            return b.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //上传文件
//    public static String httpPost(String actionUrl,Map<String,String> params,Map<String, FileBody> files){
//        String LINE_START = "--";
//        String LINE_END = "\r\n";
//        String BOUNDRY =  "*****";
//
//        try{
//            HttpURLConnection conn = null;
//            DataOutputStream dos = null;
//
//            int bytesRead, bytesAvailable, bufferSize;
//            long totalBytes;
//            byte[] buffer;
//            int maxBufferSize = 8096;
//
//            URL url = new URL(actionUrl);
//            conn = (HttpURLConnection) url.openConnection();
//
//            // Allow Inputs
//            conn.setDoInput(true);
//
//            // Allow Outputs
//            conn.setDoOutput(true);
//
//            // Don't use a cached copy.
//            conn.setUseCaches(false);
//
//            // Use a post method.
//            conn.setRequestMethod("POST");
//            //if (files != null && files.size() > 0) {
//            conn.setRequestProperty("Connection", "Keep-Alive");
//            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
//            //}
//
//            Log.i("", "cookie:" + cookie);
//            if (cookie != null) {
//                conn.setRequestProperty("Cookie", cookie);
//            }
////            // Set the cookies on the response
////            String cookie = CookieManager.getInstance().getCookie(server);
////            if (cookie != null) {
////                conn.setRequestProperty("Cookie", cookie);
////            }
//
////            // Should set this up as an option
////            if (chunkedMode) {
////                conn.setChunkedStreamingMode(maxBufferSize);
////            }
//
//            dos = new DataOutputStream(conn.getOutputStream());
//
//            // Send any extra parameters
//            for (Object key : params.keySet()) {
//                dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
//                dos.writeBytes("Content-Disposition: form-data; name=\"" +  key.toString() + "\"" + LINE_END);
//                dos.writeBytes(LINE_END);
//                dos.write(params.get(key).getBytes());
//                dos.writeBytes(LINE_END);
//
//                Log.i("", "-----key:" + key + "  value:" + params.get(key));
//            }
//            //-----------
//            if (files != null && files.size() > 0) {
//                for (String key : files.keySet()) {
//                    Log.i("", "-----key:" + key + "  value:" + params.get(key));
//                    FileBody fileBody = files.get(key);
//                    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
//                    dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\";" + " filename=\"" + fileBody.getFilename() +"\"" + LINE_END);
//                    dos.writeBytes("Content-Type: " + fileBody.getMimeType() + LINE_END);
//                    dos.writeBytes(LINE_END);
//
//                    // Get a input stream of the file on the phone
//                    InputStream fileInputStream = new FileInputStream(fileBody.getFile());
//                    bytesAvailable = fileInputStream.available();
//                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
//                    buffer = new byte[bufferSize];
//                    // read file and write it into form...
//                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//                    totalBytes = 0;
//                    while (bytesRead > 0) {
//                        totalBytes += bytesRead;
//                        //result.setBytesSent(totalBytes);
//                        dos.write(buffer, 0, bufferSize);
//                        bytesAvailable = fileInputStream.available();
//                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
//                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//                    }
//                    dos.writeBytes(LINE_END);
//                    // close streams
//                    fileInputStream.close();
//                }
//            }
//            dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);
//            dos.flush();
//            dos.close();
//
//            int statusCode = conn.getResponseCode();
//            Log.i("", "---------------statusCode:" + statusCode);
//            if (statusCode != 200) {
//                throw new HttpRequestException("server error");
//            }
//
//            //------------------ read the SERVER RESPONSE
//            InputStream is = conn.getInputStream();
//            int ch;
//            StringBuilder b = new StringBuilder();
//            while ((ch = is.read()) != -1) {
//                b.append((char) ch);
//            }
//            conn.disconnect();
//
//            return b.toString();
//        }catch(Exception e){
//            Log.i("", "---------------" + e.getMessage(), e.fillInStackTrace());
//            e.printStackTrace();
//        }
//        return null;
//    }



}
